# -*- coding: utf-8 -*-
'''
Created on Sep 8, 2012

@author: bbg
'''
import datetime
from logic.login_session_mgr import LoginSessionMgr
from core.util.debug import Log
from core.db.company_management.company import Company
from core.db.company_management.cdkey import Cdkey
from core.db.company_management import *
import json
from sqlalchemy.orm import class_mapper
from webob import Request, Response
from service.server_config import SrvConfig

def application(environ, start_response):
    '''
        entrance of apache wsgi application
    '''    
    req = Request(environ)
    res = Response()
    
    CompanyMgrService.process(req, res)
    
    return res(environ, start_response)    


class CompanyMgrService(object):
    '''
        艾云总部管理的相关信息：
        1 全局权限定义表
        2 全局区域表
        3 全局公司信息表
        4 全局CDKEY表
    '''
    __setup__ = False
    log = None    

    @staticmethod
    def process(req, res):
        if CompanyMgrService.__setup__ == False:
            Log.setPath(SrvConfig.getLogPath())
            CompanyMgrService.log = Log()            
            CompanyMgrService.__setup__ = True
                     
        try:            
            dbsession = SrvConfig.getDefaultDBSession() 
            company_id = req.params["company_id"]
            username = req.params["username"]
            token = req.params["token"]
            #检查 TOKEN 的有效性
            if LoginSessionMgr.isSessionValid(company_id, username, token, dbsession) is False:
                res.json = {'ret':107, 'msg':'token is invalid'}
                return
            
            companyMgrSrv = CompanyMgrService(dbsession)            
            if req.params['method'] == 'get':
                companyMgrSrv.getCompanyMgrInfo(req, res)
            elif req.params['method'] == 'set':
                companyMgrSrv.setCompanyMgrInfo(req, res)
            else:
                res.json = {'ret':-1, 'msg':'unknown method %s' % req.params['method']}
        except Exception,e:
            res.json = {'ret':-1, 'msg':'exception'}
            CompanyMgrService.log.e('CompanyMgrService:process, exception %s' % e)
        finally:
            dbsession.close()            
            
            
    def __init__(self, dbsession):
        self.dbsession = dbsession
        

    def getCompanyMgrInfo(self, req, res):
        '''
            客户需要获取基本信息 比如：权限，区域        
        '''                
        config_table = req.params['type']
        
        CompanyMgrService.log.d("tablename:%s" % config_table)
        config_table_classes = {}         
        config_table_classes["regions"] = regions.Regions
        config_table_classes["rights"] = rights.Rights 
        config_table_classes["company"] = company.Company  
        config_table_classes["cdkey"] = cdkey.Cdkey             
        
        config_orderby = {}
        config_orderby["regions"] ="`range` asc "
        config_orderby["rights"] = "id"
        config_orderby["company"] = "region_id asc,id asc "
        config_orderby["cdkey"] = "shop_id asc,id asc "
                                  
        if config_table in config_table_classes:
            table_class = config_table_classes[config_table]
            orderby = config_orderby[config_table]
            return self._getCompanyMgrInfoByTable(req, res, table_class, orderby)
        else:            
            res.json = {'ret':-1, 'msg': 'unknown configure'}
            CompanyMgrService.log.e('CompanyMgrService:getCompanyMgrInfo, unknown configure')


    def _getCompanyMgrInfoByTable(self, req, res, table_class, orderby):
        '''
            对读配置的表的响应
            table_class 要操作的表对应的ORM类
        '''
        try:

            #过滤出要更新的表字段名和字段值
            company_id = req.params['company_id']                     
            #获取记录操作
            if (table_class == company.Company):
                query_result = self.dbsession.query(table_class).filter(Company.id == company_id).order_by(orderby).all()
            elif (table_class==cdkey.Cdkey):
                query_result = self.dbsession.query(table_class).filter(Cdkey.company_id == company_id).order_by(orderby).all()
            else:
                query_result = self.dbsession.query(table_class).filter().order_by(orderby).all()
            
            table_fields = {}                       
            for col in (class_mapper(table_class).mapped_table.c):
                table_fields[col.name]=col.name
                                                                                           

            returnlist = []                           
            dicmy = {}
            dicmy["ret"] = 0
            dicmy["msg"] = 'success'
            icount=0
            for r in query_result:
                icount = 1
                dicmyFF = {} 
                for field in  table_fields:
                    temp = getattr(r, table_fields[field])                  
                    if type(temp) is datetime.datetime:
                        dicmyFF[field] = str(temp)                        
                    else:
                        dicmyFF[field] = temp
                    
                strtemp = json.dumps(dicmyFF)                
                returnlist.append(strtemp)
                            
            if icount == 0:                                         
                res.json = {'ret':6, 'msg':'record is empty'}
                CompanyMgrService.log.d('CompanyMgrService._getCompanyMgrInfoByTable: record is empty')
                return 
                                         
            dicmy['data'] = returnlist
             
            res.json = dicmy       
        except Exception, e:
            res.json = {'ret':-1, 'msg':'invalid params'}
            CompanyMgrService.log.e('CompanyMgrService._getCompanyMgrInfoByTable: exception:%s' % e)
            
        
            
            

    def setCompanyMgrInfo(self, req, res):
        '''
            修改  添加  删除  相关的信息 
        '''
        config_table = req.params['config_table']
        
        config_table_classes = {}
        config_table_classes["regions"] = regions.Regions
        config_table_classes["rights"] = rights.Rights 
        config_table_classes["company"] = company.Company  
        config_table_classes["cdkey"] = cdkey.Cdkey                       
        
        if config_table in config_table_classes:
            table_class = config_table_classes[config_table]
            return self._setConfigAction(req, res, table_class)
        else:
            return self.response(-1, "unknown configure")
        
 

        
    def _setConfigAction(self, req, res, table_class):
        '''
            对写配置的响应
            table_class 要操作的表对应的ORM类
        '''
        try:

            cmd = req.params['cmd']
            #过滤出要更新的表字段名和字段值
            exclude_fields = ['company_id','op_shop_id', 'username', 
                              'token', 'cmd', 'config_table', 'where_name', 
                              'where_value', 'sign']
            
            table_fields = {}
            for param in req.params.keys():
                if param not in exclude_fields:
                    table_fields[param] = req.params[param]
            
            if cmd == 'add':                
                # 增加记录操作                
                table_object = table_class()
                for field in table_fields:
                    table_object.__setattr__(field, table_fields[field])
                    
                try:
                    self.dbsession.add(table_object)
                    self.dbsession.commit()
                except Exception, e:
                    CompanyMgrService.log.e("CompanyMgrService._setConfigAction() add table %s failed" % table_object)
                    res.json = {'ret':-1, 'msg': 'add failed'}
                    return                     
                
                res.json = {"ret":0,"msg":"add ok"}                
            elif cmd == 'update':
                
                #更新记录操作
                #获取要修改的表where字段
                where_name = req.params['where_name']
                where_value = req.params['where_value']
                #get the column attribute
                columnAttr = getattr(table_class, where_name)
                
                query_result = self.dbsession.query(table_class).filter(columnAttr == where_value)
                
                if query_result.count() ==0:                   
                    CompanyMgrService.log.e("CompanyMgrService._setConfigAction(): no such record")
                    res.json = {'ret':-1, 'msg':'no such record'}
                    return
                
                for table_object in query_result:
                    for field in table_fields:
                        table_object.__setattr__(field, table_fields[field])
                        
                self.dbsession.commit()
                
                res.json = {'ret':0, 'msg' : 'update ok'}
                return
            elif cmd == 'del':                
                #删除记录操作 目前没有用到
                
                where_name = req.params['where_name']
                where_value = req.params['where_value']
                #get the column attribute
                columnAttr = getattr(table_class, where_name)
                
                self.dbsession.query(table_class).filter(columnAttr == where_value).delete()
                self.dbsession.commit()
                                
                res.josn ={'ret':0, 'msg' : 'delete ok'}
        except Exception, e:             
            CompanyMgrService.log.e('CompanyMgrService._setConfigAction(): exception:%s' % e)
            res.json = {'ret':-1, 'msg':'unknown exception'}
                